package com.thenie.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thenie.seckill.mapper.UserMapper;
import com.thenie.seckill.pojo.User;
import com.thenie.seckill.service.IUserService;
import com.thenie.seckill.util.CookieUtil;
import com.thenie.seckill.util.JsonUtil;
import com.thenie.seckill.util.MD5Util;
import com.thenie.seckill.util.UUIDUtil;
import com.thenie.seckill.vo.LoginVo;
import com.thenie.seckill.vo.RespBean;
import com.thenie.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author thenie
 * @since 2022-04-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,Object> redis;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();


        User user = userMapper.selectById(mobile);

        if (user==null){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }

        String inputPassword = MD5Util.formPassToDBPass(password, user.getSalt());
        //判断密码是否正确
        if (!inputPassword.equals(user.getPassword())){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        //生成cookie保存到redis中
        String ticket = UUIDUtil.uuid();
//        request.getSession().setAttribute(ticket, user);
        redis.opsForValue().set("user:"+ticket, JsonUtil.object2JsonStr(user),1, TimeUnit.DAYS);
        CookieUtil.setCookie(request,response,"userTicket", ticket);

        return RespBean.success(ticket);
    }

    @Override
    public User getUserByCookie(String ticket, HttpServletRequest request, HttpServletResponse response) {
        User user =null;
        if (StringUtils.isEmpty(ticket)){
            return null;
        }

        String userStr = (String)redis.opsForValue().get("user:" + ticket);
        if (userStr!=null){
            user = JsonUtil.jsonStr2Object(userStr, User.class);
        }
        if (null != user){
            CookieUtil.setCookie(request,response,"userTicket",ticket);
        }

        return user;
    }


}
